package org.bing.engine.console.service;

import java.sql.SQLException;

import org.bing.engine.common.logging.Log;
import org.bing.engine.common.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class AbstractHibernateManager {
    protected static final Log logger = LogFactory.getLog(AbstractHibernateManager.class);
    protected HibernateTemplate template;

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    public String findUniqueString(final String hql, final Object[] args) {
        Object result = template.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(hql);
                if (args != null) {
                    for (int i = 0; i < args.length; i++) {
                        query.setParameter(i, args[i]);
                    }
                }
                return query.uniqueResult();
            }
        });

        return result == null ? null : result.toString();
    }

    public Object findUniqueObject(final String hql, final Object[] args) {
        Object result = template.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(hql);
                if (args != null) {
                    for (int i = 0; i < args.length; i++) {
                        query.setParameter(i, args[i]);
                    }
                }
                return query.uniqueResult();
            }
        });

        return result;
    }
    
    public Object excuteHql(final String hql, final Object arg) {
        return excuteHql(hql, new Object[] { arg });
    }

    public Object excuteHql(final String hql, final Object[] args) {
        return template.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(hql);
                if (args != null) {
                    for (int i = 0; i < args.length; i++) {
                        query.setParameter(i, args[i]);
                    }
                }
                int num = query.executeUpdate();
                return num;
            }
        });
    }
}
